package com.bawei.module_mine.ui

import android.content.Intent
import android.graphics.Color
import android.text.SpannableStringBuilder
import android.text.Spanned
import android.text.method.LinkMovementMethod
import android.text.style.ClickableSpan
import android.text.style.ForegroundColorSpan
import android.util.Log
import android.view.View
import android.widget.Toast
import androidx.lifecycle.Lifecycle
import androidx.lifecycle.ViewModelProvider
import androidx.lifecycle.lifecycleScope
import androidx.lifecycle.repeatOnLifecycle
import cn.jiguang.verifysdk.api.AuthPageEventListener
import cn.jiguang.verifysdk.api.JVerificationInterface
import cn.jiguang.verifysdk.api.JVerifyUIConfig
import cn.jiguang.verifysdk.api.LoginSettings
import cn.jiguang.verifysdk.api.PreLoginListener
import cn.jiguang.verifysdk.api.VerifyListener
import com.alibaba.android.arouter.facade.annotation.Route
import com.alibaba.android.arouter.launcher.ARouter
import com.bawei.lib_common.base.utils.LoggerUtils
import com.bawei.lib_mvi.Router
import com.bawei.lib_mvi.base.BaseActivity
import com.bawei.lib_mvi.base.BaseMVIActivity
import com.bawei.lib_storage.mmkv.AuthMMKV
import com.bawei.module_mine.R
import com.bawei.module_mine.databinding.ActivityLoginBinding
import com.bawei.module_mine.http.intent.LoginIntent
import com.bawei.module_mine.http.state.LoginState
import com.bawei.module_mine.http.viewModel.LoginViewModel
import com.bawei.module_mine.model.AddAccountModel
import com.bawei.module_mine.model.Card
import com.bawei.module_mine.model.GetPermissions
import com.blankj.utilcode.util.SPUtils
import com.tencent.mmkv.MMKV
import kotlinx.coroutines.flow.collect
import kotlinx.coroutines.launch
import org.json.JSONObject

@Route(path = Router.Ui.USER_ACTIVITY)
class LoginActivity : BaseMVIActivity() {

    private val binding by lazy {
        ActivityLoginBinding.inflate(layoutInflater)
    }

    private lateinit var mViewModel: LoginViewModel

    override fun getLayoutRootView(): View {
        return binding.root
    }

    override fun generateViewModel() {
        mViewModel = ViewModelProvider(this)[LoginViewModel::class.java]
    }

    //增加一个字段存储预取号接口状态
    private var finishPrelogin = true

    // 极光授权页事件类型
    companion object {
        private const val EVENT_OPEN_AUTH_PAGE_SUCCESS = 1 //授权页打开
        private const val EVENT_OPEN_AUTH_PAGE_FAIL = 2  //授权页打开失败
        private const val EVENT_CLOSE_AUTH_PAGE = 3 //关闭授权页
        private const val EVENT_CLICK_LOGIN_BTN = 4 //点击登录按钮
        private const val EVENT_CLICK_CHECKBOX = 5 //点击协议复选框
        private const val EVENT_CLICK_PRIVACY = 6 //点击隐私协议
    }


    override fun initView() {
        super.initView()
        preLogin()
        binding.tvHelp.setOnClickListener {
            ARouter.getInstance().build(Router.Ui.HELP_ACTIVITY).navigation()
        }
        val spannable = SpannableStringBuilder(binding.tvPrivacy.text.toString())
        val spannable1 = SpannableStringBuilder(binding.tvProtocol.text.toString())
        val spannable2 = SpannableStringBuilder(binding.tvLogin.text.toString())
        spannable.setSpan(object : ClickableSpan() {
            override fun onClick(p0: View) {
                ARouter.getInstance().build(Router.Ui.WEB_ACTIVITY)
                    .withString(
                        "url",
                        "https://terms.alicdn.com/legal-agreement/terms/suit_bu1_unification/suit_bu1_unification202005142208_14749.html"
                    )
                    .navigation()
            }
        }, 0, 4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
        spannable.setSpan(
            ForegroundColorSpan(Color.parseColor("#807F7F")),
            0,
            4,
            Spanned.SPAN_EXCLUSIVE_INCLUSIVE
        )
        binding.tvPrivacy.setText(spannable)
        binding.tvPrivacy.setMovementMethod(LinkMovementMethod.getInstance())
        spannable1.setSpan(object : ClickableSpan() {
            override fun onClick(p0: View) {
                ARouter.getInstance().build(Router.Ui.WEB_ACTIVITY)
                    .withString(
                        "url",
                        "https://www.douyin.com/draft/douyin_agreement/douyin_agreement_privacy.html?id=6773901168964798477"
                    )
                    .navigation()
            }
        }, 0, 4, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
        spannable1.setSpan(
            ForegroundColorSpan(Color.parseColor("#807F7F")),
            0,
            4,
            Spanned.SPAN_EXCLUSIVE_INCLUSIVE
        )
        binding.tvProtocol.setText(spannable1)
        binding.tvProtocol.setMovementMethod(LinkMovementMethod.getInstance())
        spannable2.setSpan(object : ClickableSpan() {
            override fun onClick(p0: View) {
                ARouter.getInstance().build(Router.Ui.NATIVE_LOGIN_ACTIVITY).navigation()
            }
        }, 0, 2, Spanned.SPAN_EXCLUSIVE_INCLUSIVE)
        spannable2.setSpan(
            ForegroundColorSpan(Color.parseColor("#807F7F")),
            0,
            2,
            Spanned.SPAN_EXCLUSIVE_INCLUSIVE
        )
        binding.tvLogin.setText(spannable2)
        binding.tvLogin.setMovementMethod(LinkMovementMethod.getInstance())
        binding.ivClose.setOnClickListener {
            finish()
        }
        binding.btnLogin.setOnClickListener {
            MMKV.defaultMMKV().encode("token", SPUtils.getInstance().getString("token"))
            if (GetPermissions.hasAllPermissions(this)) {
                ARouter.getInstance().build(Router.Ui.MainActivity).navigation()
            } else {
                ARouter.getInstance().build(Router.Ui.PHONE_BOOK_ACTIVITY).navigation()
            }
        }

    }

    private fun preLogin() {
        //判断SDK初始化状态
        if (JVerificationInterface.isInitSuccess()) {
            this.finishPrelogin = false
            JVerificationInterface.preLogin(this, 5000, object : PreLoginListener {

                override fun onResult(p0: Int, p1: String?, p2: JSONObject?) {
                    Log.d("Login", "preLogin: $p0 $p1")
                    Log.d("Login", "preLogin: $p2")
                    finishPrelogin = true

                    loginAuth()

                }
            })
        }
    }

    private fun loginAuth() {
        val settings = LoginSettings();
        settings.isAutoFinish = true;// 设置登录完成后是否自动关闭授权页
        settings.timeout = 15 * 1000;// 设置超时时间，单位毫秒。 合法范围（0，30000], 范围以外默认设置为 10000
        settings.authPageEventListener = object : AuthPageEventListener() {
            override fun onEvent(p0: Int, p1: String?) {
                when (p0) {
                    EVENT_OPEN_AUTH_PAGE_SUCCESS -> {
                        Log.d("JVerify", "授权页打开成功")
                    }
                    EVENT_OPEN_AUTH_PAGE_FAIL -> {
                        Log.d("JVerify", "授权页打开失败: $p1")
                    }
                    EVENT_CLOSE_AUTH_PAGE -> {
                        Log.d("JVerify", "授权页关闭")
                    }
                    EVENT_CLICK_LOGIN_BTN -> {
                        Log.d("JVerify", "点击登录按钮")
                    }
                    EVENT_CLICK_CHECKBOX -> {
                        Log.d("JVerify", "点击协议复选框")
                    }
                    EVENT_CLICK_PRIVACY -> {
                        Log.d("JVerify", "点击隐私协议")
                    }
                    else -> {
                        Log.d("JVerify",
                            "其他事件: $p0 $p1")
                    }
                }
            }
        }

        val uiConfig = JVerifyUIConfig.Builder()
            .setNavColor(Color.WHITE) // 顶部导航栏颜色
            .setNavText("帮助")
            .setNavTextColor(Color.BLACK)
            .setNavReturnImgPath("close_blackgray") // 左上角叉号
            .setLogoImgPath("ic_person") // 中间用户头像
            .setLogoWidth(100)
            .setLogoHeight(100)
            .setLogoOffsetY(80)
            .setLogoHidden(false)
            .setNumberColor(Color.BLACK)
            .setNumFieldOffsetY(200)
            .setLogBtnText("本机号码一键登录")
            .setLogBtnTextColor(Color.WHITE)
            .setLogBtnImgPath("btn_login_bg") // 你自定义的按钮背景图片名
            .setLogBtnOffsetY(300)
            .setLogBtnHeight(50)
            .setLogBtnWidth(300)
            .setPrivacyState(false)
            .setPrivacyOffsetY(370)
            .setAppPrivacyOne("用户协议", "https://your_user_agreement_url")
            .setAppPrivacyTwo("隐私政策", "https://your_privacy_policy_url")
            .setPrivacyText("登录则表示同意", "和用户协议及隐私政策")
            .setSloganOffsetY(250)
            .setSloganTextColor(Color.GRAY)
            .build()

        JVerificationInterface.setCustomUIWithConfig(uiConfig)

        // 拉起授权页面
        JVerificationInterface.loginAuth(
            this, settings,
            VerifyListener { code, content, operator, operatorReturn ->
                Log.d("LoginActivity", "code: $code ")
                Log.d("LoginActivity", "content: $content ")
                Log.d("LoginActivity", "operator: $operator ")
                Log.d("LoginActivity", "operatorReturn: $operatorReturn ")

                if (code == 6000) {
                    // 1. 极光一键登录成功，发送loginToken到服务器校验
                    lifecycleScope.launch {
                        repeatOnLifecycle(Lifecycle.State.RESUMED) {
                            mViewModel.intents.send(LoginIntent.QuickLogin("3", content))
                        }
                    }
                    // 2. 不要在这里直接跳转页面或保存token，等服务器校验通过后再处理
                } else {
                    runOnUiThread {
                        Toast.makeText(this, "一键登录失败", Toast.LENGTH_SHORT).show()
                    }
                }
            })
    }

    override fun handleState() {
        lifecycleScope.launch {
            repeatOnLifecycle(Lifecycle.State.RESUMED) {
                mViewModel.state.collect {
                    when (it) {
                        is LoginState.QuickLoginSuccess -> {
                            // 3. 服务器校验通过后，保存token并跳转页面
                            MMKV.defaultMMKV().encode("token", SPUtils.getInstance().getString("token"))
                            if (GetPermissions.hasAllPermissions(this@LoginActivity)) {
                                ARouter.getInstance().build(Router.Ui.MainActivity).navigation()
                            } else {
                                ARouter.getInstance().build(Router.Ui.PHONE_BOOK_ACTIVITY).navigation()
                            }
                            finish()
                        }
                        else -> {
                            // 失败处理（可选）
                        }
                    }
                }
            }
        }
    }

    override fun onResume() {
        super.onResume()
//        val phone = AuthMMKV.username
//        if (!phone.isNullOrEmpty()) {
//            binding.tvUsername.setText(GetPermissions.desensitizePhoneNumber(phone))
//        }
    }
}